BST Deletion: Preserving the Invariant
Removing a node from a BST must maintain the ordering invariant. The complexity of deletion depends on the node's children count:
- Case 1: Node is a Leaf (0 Children): Simply remove the node and update the parent pointer to `NULL`.
- Case 2: Node has 1 Child: Replace the node with its sole child. The child takes the node's position and inherits its parent.
- Case 3: Node has 2 Children (The Complex Case): The node must be replaced by either its In-Order Successor (the smallest key in the right subtree) or its In-Order Predecessor (the largest key in the left subtree). Replacing the node with the successor (S) ensures the BST property holds, and S is guaranteed to have at most one child (simplifying the recursive deletion of S).
Preventing Skew: The Need for Balancing
Repeated insertions/deletions can lead to a skewed (degenerate) tree structure, where the BST acts like a linked list, degrading efficiency from $O(\log N)$ to $O(N)$. Self-balancing trees (like AVL Trees) address this using Balance Factors (BF) and Rotations.
| Operation | Unbalanced BST (Worst Case) | Balanced BST (AVL/Red-Black) |
|---|---|---|
| Search | $O(H) \implies O(N)$ | $O(\log N)$ |
| Insertion | $O(H) \implies O(N)$ | $O(\log N)$ |
| Deletion | $O(H) \implies O(N)$ | $O(\log N)$ |
The Balance Factor is calculated as: $BF = \text{Height}(L_{subtree}) - \text{Height}(R_{subtree})$. An AVL tree requires $|BF| \le 1$ for every node.
Rotation Mechanics: Restoring Balance
Rotations are local structural adjustments that restore the balance factor constraint while preserving the overall BST property.
⚙️ Quick Guide: Single Rotation (RR Example)
Rotations essentially pivot the structure around a specific node to move deeper nodes closer to the root, shortening the overall height.
- Identify the Pivot (Z): The first node encountered (starting from the newly inserted/deleted node) where $|BF| > 1$.
- Identify the Child (Y) and Grandchild (X): Determine the path causing the imbalance (e.g., Left-Left, Right-Right).
- Perform Rotation: A single rotation (e.g., Left Rotation for an RR violation) moves the child (Y) up into the pivot's (Z) position, transferring subtrees to maintain the ordering.
Goal: Ensure the height of the tree $H$ remains proportional to $\log N$.
1. When deleting a node with two children, which node is a valid replacement to maintain the BST property?
2. What is the primary consequence of a BST becoming skewed or degenerate?
3. In a self-balancing tree like an AVL tree, what is the maximum allowed absolute value for the Balance Factor ($|BF|$) of any node?
4. What is the main purpose of performing a rotation in a self-balancing BST?